<template>
  <el-form :model="form" label-width="120px">
    <el-form-item label="学生">
      <el-select 
        v-model="form.student_id" 
        filterable 
        placeholder="请选择学生" 
        @change="handleStudentChange"
      >
        <el-option 
          v-for="student in students" 
          :key="student.id" 
          :label="`${student.student_id} - ${student.name}`" 
          :value="student.student_id"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="姓名">
      <el-input v-model="form.name" disabled />
    </el-form-item>
    <el-form-item label="奖惩名称">
      <el-input v-model="form.reward_name" />
    </el-form-item>
    <el-form-item label="奖惩类型">
      <el-radio-group v-model="form.reward_type">
        <el-radio label="奖励">奖励</el-radio>
        <el-radio label="惩罚">惩罚</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="奖惩日期">
      <el-date-picker
        v-model="form.reward_date"
        type="date"
        placeholder="选择日期"
      />
    </el-form-item>
    <el-form-item label="备注">
      <el-input v-model="form.remark" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm">确认添加</el-button>
      <el-button @click="closeDialog">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import RewardApi from '@/api/RewardApi';

export default {
  data() {
    return {
      form: {
        student_id: '',
        name: '',
        reward_name: '',
        reward_type: '奖励', // 默认选择奖励
        reward_date: '',
        remark: '',
      },
      students: [] // 存储学生列表，包含id、student_id和name
    };
  },
  methods: {
    submitForm() {
      // 验证必填字段
      if (!this.form.student_id || !this.form.reward_name || !this.form.reward_type || !this.form.reward_date) {
        this.$message.error('请填写完整信息');
        return;
      }
      this.$emit('submit-form', this.form);
    },
    closeDialog() {
      this.$emit('close-dialog');
    },
    // 处理学生选择变化
    handleStudentChange(studentId) {
      const selectedStudent = this.students.find(student => student.student_id === studentId);
      if (selectedStudent) {
        this.form.name = selectedStudent.name;
      } else {
        this.form.name = '';
      }
    },
    // 获取学生列表
    async fetchStudents() {
      try {
        const response = await RewardApi.getStudentsForm();
        // 确保数据结构一致，包含student_id和name
        this.students = response.data.data || response.data;
      } catch (error) {
        console.error("学号姓名信息获取错误:", error);
        this.$message.error('获取学生列表失败');
      }
    }
  },
  created() {
    this.fetchStudents();
  }
};
</script>